package com.uchengwang.wxapi;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.uchengwang.functions.http.config.BaseConfig;
import com.uchengwang.functions.http.entity.MapRequest;
import com.uchengwang.functions.http.listener.OnHttpResultSingleListener;
import com.uchengwang.functions.http.listener.OnResultListener;
import com.uchengwang.ui.base_ui.ui.AllBaseActivity;
import com.uchengwang.ui.base_ui.ui.MainActivity;
import com.uchengwang.ui.cm_ui.login.LoginHttp.LoginHttpManager;
import com.uchengwang.ui.cm_ui.login.bean.WXTokenBean;
import com.uchengwang.ui.cm_ui.login.bean.WXUserInfoBean;
import com.uchengwang.ui.cm_ui.login.ui.RegisterOrFindPwActivity;
import com.uchengwang.ui.utils.ShareToWxUtils;

/**
 * Created by U城网 on 2018/1/19.
 * 微信三方登录
 */

public class WXEntryActivity extends AllBaseActivity implements IWXAPIEventHandler {

    /**
     * 微信登录相关
     */
    private IWXAPI api;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //通过WXAPIFactory工厂获取IWXApI的示例
        api = ShareToWxUtils.getUtils(this).getWXAPI(this);
        //注意：
        //第三方开发者如果使用透明界面来实现WXEntryActivity，需要判断handleIntent的返回值，如果返回值为false，则说明入参不合法未被SDK处理，应finish当前透明界面，避免外部通过传递非法参数的Intent导致停留在透明界面，引起用户的疑惑
        try {
            boolean result =  api.handleIntent(getIntent(), this);
            if(!result){
                Log.d("jjf", "参数不合法，未被SDK处理，退出");
                finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        api.handleIntent(data,this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
        finish();
    }

    @Override
    public void onReq(BaseReq baseReq) {
        Log.d("jjf", "baseReq:"+ JSON.toJSONString(baseReq));
    }

    @Override
    public void onResp(BaseResp baseResp) {
        Log.d("jjf", "baseResp:"+JSON.toJSONString(baseResp));
        String result = "";
        switch(baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                result ="发送成功";
                String code = ((SendAuth.Resp)baseResp).code;
                ShareToWxUtils.getUtils(this).getWxTokenByCode(this, code, new OnHttpResultSingleListener<WXTokenBean>() {
                    @Override
                    public void onResult(final int status, String msg, final WXTokenBean wxTokenBean) {
                        if (wxTokenBean != null){
                            MapRequest map = new MapRequest();
                            map.put(BaseConfig.OAUTH_TYPE, "WX");
                            map.put(BaseConfig.OAUTH_CODE, wxTokenBean.getUnionid());
                            LoginHttpManager.getManager().login(WXEntryActivity.this, map, new OnResultListener() {
                                @Override
                                public void onResult(int s, String msg, int total, String data) {
                                    if (s ==0){
                                        //说明之前注册了微信
                                        startActivity(new Intent(WXEntryActivity.this, MainActivity.class));
                                    }else {
                                        //之前没有注册微信  走注册流程
                                        ShareToWxUtils.getUtils(WXEntryActivity.this).getWXUserInfo(WXEntryActivity.this, wxTokenBean.getAccess_token(), wxTokenBean.getOpenid(), new OnHttpResultSingleListener<WXUserInfoBean>() {
                                            @Override
                                            public void onResult(int ss, String msg, WXUserInfoBean wxUserInfoBean) {
                                                if (wxUserInfoBean != null){
                                                    wxUserInfoBean.setOauthType(0);
                                                    Intent intent = new Intent(WXEntryActivity.this, RegisterOrFindPwActivity.class);
                                                    intent.putExtra(BaseConfig.BEAN, wxUserInfoBean);
                                                    intent.putExtra(BaseConfig.TYPE, 1);
                                                    startActivity(intent);
                                                }
                                                    WXEntryActivity.this.finish();

                                            }
                                        });

                                    }
                                }
                            });


                        }else {
                            WXEntryActivity.this.finish();
                        }
                    }
                });
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                result = "发送取消";
                Log.d("jjf", "微信返回code:"+baseResp.errCode);
                finish();
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                result = "发送被拒绝";
                Log.d("jjf", "微信返回code:"+baseResp.errCode);
                finish();
                break;
            default:
                result = "发送返回";
                Log.d("jjf", "微信返回code:"+baseResp.errCode);
                finish();
                break;
        }
    }
}